using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.PackageTypeCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.PackageTypeHandler
{
    /// <summary>
    /// 套餐类型删除事件处理器
    /// </summary>
    public class DeletedPackageTypeHandler : IRequestHandler<DeletedPackageTypeCommand, APIResult<int>>
    {
        private readonly IBaseRepository<PackageTypeModel> baseRepository;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepository">仓储</param>
        /// <param name="mapper">映射</param>
        public DeletedPackageTypeHandler(IBaseRepository<PackageTypeModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }


        /// <summary>
        /// 处理删除套餐类型事件
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">参数</param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(DeletedPackageTypeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();

                var model = baseRepository.GetAll().FirstOrDefault(x => x.PackageTypeId == request.PackageTypeId);

                model.IsDeleted = true;

                var dto = baseRepository.Update(model).Result;

                if (dto > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "删除成功";
                    result.Data = dto;
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "删除失败";
                    return await Task.FromResult(result);
                }
                return await Task.FromResult(result);


            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
